<template>
  <table class="custom-table">
    <thead>
      <tr>
        <th v-for="col in columns" :key="col.key" @click="col.sortable ? sortBy(col.key) : null" :class="{ sortable: col.sortable, sorted: sortKey === col.key }">
          {{ col.title }}
          <span v-if="col.sortable">
            <span v-if="sortKey === col.key">
              {{ sortOrder === 'asc' ? '▲' : '▼' }}
            </span>
            <span v-else>⇅</span>
          </span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, rowIndex) in sortedData" :key="rowIndex">
        <td v-for="col in columns" :key="col.key">
          <slot :name="`cell-${col.key}`" :row="row" :value="row[col.key]">
            {{ row[col.key] }}
          </slot>
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  columns: {
    type: Array,
    required: true
    // 每个列对象示例：{ key: 'name', title: '姓名', sortable: true }
  },
  data: {
    type: Array,
    required: true
  }
})

const sortKey = ref(null)
const sortOrder = ref('asc')

const sortBy = key => {
  if (sortKey.value === key) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortKey.value = key
    sortOrder.value = 'asc'
  }
}

const sortedData = computed(() => {
  if (!sortKey.value) return props.data
  return [...props.data].sort((a, b) => {
    if (a[sortKey.value] === b[sortKey.value]) return 0
    if (sortOrder.value === 'asc') {
      return a[sortKey.value] > b[sortKey.value] ? 1 : -1
    } else {
      return a[sortKey.value] < b[sortKey.value] ? 1 : -1
    }
  })
})
</script>

<style scoped>
.custom-table {
  width: 100%;
  border-collapse: collapse;
}
.custom-table th,
.custom-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}
.custom-table th.sortable {
  cursor: pointer;
  user-select: none;
}
.custom-table th.sorted {
  background-color: #f0f0f0;
}
</style>
